<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useExhibitionHeaderStore } from '../../store/exhibition/exhibitionHeaderStore'
import { useAddExhibitionStore } from '../../store/exhibition/addExhibitionStore'
import { useExhibitionStore } from '../../store/exhibition/exhibitionStore'
import { ElMessage } from 'element-plus'
import { useImgStore } from '../../store/img'
import uploadImg from '../uploadImg.vue'
import UploadImg from '../../api/uploadImg'
import api from '../../api/classification'

// 引入store
const exhibitionHeaderStore = useExhibitionHeaderStore()
const addExhibitionStore = useAddExhibitionStore()
const exhibitionStore=useExhibitionStore()
const imgStore = useImgStore()



// 表单数据
const formData = reactive({
    exhibitionName: '',
    exhibitionDescription: '',
    exhibitionType: '',
    startTime: '',
    endTime: '',
    exhibitionAddress: '',
    exhibitionStatus: '0',
    classificationIds: []
})

// 表单验证规则
const rules = {
    exhibitionName: [
        { required: true, message: '请输入展览名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    exhibitionDescription: [
        { required: true, message: '请输入展览描述', trigger: 'blur' }
    ],
    exhibitionType: [
        { required: true, message: '请选择展览类型', trigger: 'change' }
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    exhibitionAddress: [
        { required: true, message: '请输入展览地点', trigger: 'blur' }
    ],
    exhibitionStatus: [
        { required: true, message: '请选择展览状态', trigger: 'change' }
    ]
}

// 表单引用
const formRef = ref()

// 是否为常设展览
const isPermanent = computed(() => formData.exhibitionType === '常设展览')

// 监听展览类型变化，如果是常设展览，清空结束时间
watch(() => formData.exhibitionType, (newVal) => {
    if (newVal === '1') {
        formData.endTime = ''
    }
})



// 获取分类列表
const fetchClassifications = async () => {
    try {
        const res = await api.getClassificationCategory()
        if (res.data && res.data.code === 200) {
            console.log('分类列表:', res.data.data)
            addExhibitionStore.categoryList = res.data.data
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            // 检查是否上传了封面
            if (!imgStore.imgUrl) {
                ElMessage.warning('请上传展览封面')
                return
            }

            try {
                const submitData = {
                    name: formData.exhibitionName,
                    description: formData.exhibitionDescription,
                    exhiType: formData.exhibitionType,
                    startDate: formData.startTime,
                    endDate: isPermanent.value ? null : formData.endTime,
                    location: formData.exhibitionAddress,
                    status: formData.exhibitionStatus,
                    coverImage: imgStore.imgUrl,
                    exhiClass: formData.classificationIds
                }
                // 构建提交数据
                await UploadImg.uploadImg(imgStore.imgRow).then((res) => { 
                    submitData.coverImage = res.data.data
                })

                // 调用添加展览API
                await addExhibitionStore.addExhibition(submitData)

                ElMessage.success('添加展览成功')
                addExhibitionStore.setIsOpen(false)
                resetForm()
                exhibitionStore.getExhibitionList()
            } catch (error) {
                console.error('添加展览失败:', error)
                ElMessage.error('添加展览失败')
            } finally{
                exhibitionStore.changeLoading()
            }
        } else {
            ElMessage.warning('请完善表单信息')
            return false
        }
    })
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    formData.exhibitionName = ''
    formData.exhibitionDescription = ''
    formData.exhibitionType = ''
    formData.startTime = ''
    formData.endTime = ''
    formData.exhibitionAddress = ''
    formData.exhibitionStatus = '0'
    formData.classificationIds = []
    imgStore.setImgUrlNull()
    imgStore.setImgRowNull()
}

onMounted(async () => {
    await fetchClassifications()
})
</script>

<template>
    <el-dialog v-model="addExhibitionStore.isOpen" title="添加展览" width="650px" destroy-on-close
        :close-on-click-modal="false">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="exhibition-form">
            <el-row :gutter="20">
                <!-- 左侧表单 -->
                <el-col :span="10">
                    <el-form-item label="展览名称" prop="exhibitionName">
                        <el-input v-model="formData.exhibitionName" placeholder="请输入展览名称" />
                    </el-form-item>

                    <el-form-item label="展览类型" prop="exhibitionType">
                        <el-select v-model="formData.exhibitionType" placeholder="请选择展览类型" class="w-100">
                            <el-option
                                v-for="item in exhibitionHeaderStore.exhibitionTypes.filter(item => item.value !== '')"
                                :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="开始时间" prop="startTime">
                        <el-date-picker v-model="formData.startTime" type="date" placeholder="选择开始日期" class="w-100" />
                    </el-form-item>

                    <el-form-item label="结束时间" prop="endTime" v-if="!isPermanent">
                        <el-date-picker v-model="formData.endTime" type="date" placeholder="选择结束日期" class="w-100"
                            :disabled="isPermanent" />
                    </el-form-item>

                    <el-form-item label="展览地点" prop="exhibitionAddress">
                        <el-input v-model="formData.exhibitionAddress" placeholder="请输入展览地点" />
                    </el-form-item>

                    <el-form-item label="展览状态" prop="exhibitionStatus">
                        <el-select v-model="formData.exhibitionStatus" placeholder="请选择展览状态" class="w-100">
                            <el-option
                                v-for="item in exhibitionHeaderStore.exhibitionStatus.filter(item => item.value !== '')"
                                :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="藏品分类">
                        <el-cascader v-model="formData.classificationIds"
                            :options="addExhibitionStore.categoryList" :props="{
                                multiple: true,
                                checkStrictly: true,
                                label: 'label',
                                value: 'value',
                                emitPath: false
                            }" placeholder="请选择藏品分类" clearable class="w-100" />
                    </el-form-item>
                </el-col>

                <!-- 右侧封面上传和描述 -->
                <el-col :span="10">
                    <el-form-item label="展览描述" prop="exhibitionDescription">
                        <el-input v-model="formData.exhibitionDescription" type="textarea" :rows="5"
                            placeholder="请输入展览描述" />
                    </el-form-item>
                    <el-form-item label="展览封面" class="upload-container">
                        <div class="upload-wrapper">
                            <uploadImg />
                            <div class="upload-tip">请上传展览封面图片</div>
                        </div>
                    </el-form-item>

                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addExhibitionStore.setIsOpen(false)">取消</el-button>
                <el-button type="primary" @click="submitForm">确认添加</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
.exhibition-form {
    margin-top: 20px;
}

.w-100 {
    width: 100%;
}

.upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.upload-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 10px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .el-dialog {
        width: 95% !important;
    }

    .el-row {
        display: flex;
        flex-direction: column;
    }

    .el-col {
        width: 100% !important;
    }
}
</style>